#!/bin/ash -efu
#
# mki-pack-cpio
#
# This file is part of mkimage
# Copyright (C) 2008-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${0%/*}"/mki-sh-functions

verbose "has started executing."

pkgs="${PACKAGES_REQUIRED_PACK_CPIO:-}"

outname="${MKI_OUTNAME:-outname}"
outname="${outname##*/}"

imgsubdir="${MKI_IMAGESUBDIR:-}"
imgsubdir="${imgsubdir#/}"

[ "$MKI_OUTNAME" = "${MKI_OUTNAME##*/}" ] ||
	outdir="$(readlink -ev "${MKI_OUTNAME%/*}")"

compress='cat'
case "${MKI_CPIO_COMPRESS:-}" in
	xz)
		compress='xz'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_XZ:-}"
		;;
	gzip|gz)
		compress='gzip'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_GZIP:-}"
		;;
	bzip2|bz2)
		compress='bzip2'
		pkgs="$pkgs  ${PACKAGES_REQUIRED_PACK_BZIP2:-}"
		;;
	zst|zstd)
		compress='zstd'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_ZSTD:-}"
		;;
	lz4)
		compress='lz4'
		pkgs="$pkgs ${PACKAGES_REQUIRED_PACK_LZ4:-}"
		;;
esac

[ -d "$chroot" ] ||
	fatal "$dir: not look like a work directory of hasher."

mki-install $pkgs ||
	fatal "failed to install packages: $pkgs."

run_chrooted "$chroot" > "$outdir/$outname" <<EOF
#!/bin/sh -efu
cd /.image/

[ -z "$imgsubdir" ] || [ ! -d "./$imgsubdir" ] || cd "./$imgsubdir"

args=
[ ! -d .in ]       || args="\${args:+\$args -a} ! -wholename ./.in"
[ ! -d .host ]     || args="\${args:+\$args -a} ! -wholename ./.host"
[ ! -f .fakedata ] || args="\${args:+\$args -a} ! -wholename ./.fakedata"

for dir in ${MKI_EXCLUDE:-}; do
	dir="${dir#/}"
	[ ! -d "./$dir" ] || args="\${args:+\$args -a} ! -wholename ./$dir"
done

find . -mindepth 1 \$args -print0 -o -prune |
	cpio $verbose -0 -o -c |
	$compress
EOF
